package org.micro.frame.mybatis.datasource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.micro.frame.mybatis.configuration.BaseDataSourceConfig;
import org.micro.frame.mybatis.configuration.MultipleDataSource;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@MultipleDataSource("test2")
@MapperScan(basePackages = "org.micro.frame.mybatis.mapper.test2", sqlSessionTemplateRef = "test2SqlSessionTemplate")
public class Test2DataSourceConfig extends BaseDataSourceConfig {

    @Autowired
    @Qualifier("test2DataSource")
    private DataSource dataSource;

    @Autowired
    @Qualifier("test2SqlSessionFactory")
    private SqlSessionFactory sqlSessionFactory;

    @Bean(name = "test2DataSource")
    @ConfigurationProperties(prefix = "spring.multiple-datasource.test2")
    public DataSource dataSource() {
        return super.buildDataSource();
    }

    @Bean(name = "test2SqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory() {
        return super.buildSqlSessionFactory(dataSource);
    }

    @Bean(name = "test2DataSourceTransactionManager")
    public DataSourceTransactionManager dataSourceTransactionManager() {
        return super.buildDataSourceTransactionManager(dataSource);
    }

    @ConditionalOnClass(SqlSessionFactory.class)
    @Bean(name = "test2SqlSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate() {
        return super.buildSqlSessionTemplate(sqlSessionFactory);
    }

}
